package controller

import (
	"fmt"
	"github.com/astaxie/beego"
	"github.com/astaxie/beego/logs"
	_ "github.com/go-sql-driver/mysql"
	"github.com/jmoiron/sqlx"
	"minishop/domain/repository"
)

var (
    Db *sqlx.DB
	err error
	//shopConfig = &ShopConfig{}
)


type ShopController struct {
	beego.Controller
}

type ShopConfig struct {
	RedisAddr string
	RedisPort string
	DbDriver string
	DbUser string
	DbPwd string
	DbHost string
	DbPort string
	DbDatabase string
	DbProtocol string
}

func initAppConfig() (shopConfig *ShopConfig)  {
	shopConfig = &ShopConfig{}
	redisAddr := beego.AppConfig.String("redis_addr")
	redisPort := beego.AppConfig.String("redis_port")
	dbDriver := beego.AppConfig.String("db_driver")
	dbUser := beego.AppConfig.String("db_user")
	dbPwd := beego.AppConfig.String("db_pwd")
	dbHost := beego.AppConfig.String("db_host")
	dbPort := beego.AppConfig.String("db_port")
	dbDatabase := beego.AppConfig.String("db_database")
	dbProtocol := beego.AppConfig.String("db_protocol")

	shopConfig.RedisAddr = redisAddr
	shopConfig.RedisPort = redisPort
	shopConfig.DbDriver = dbDriver
	shopConfig.DbUser = dbUser
	shopConfig.DbPwd = dbPwd
	shopConfig.DbHost = dbHost
	shopConfig.DbPort = dbPort
	shopConfig.DbDatabase = dbDatabase
	shopConfig.DbProtocol = dbProtocol
	return
}

func init(){
	config := initAppConfig()
	sqlPrameter := fmt.Sprintf("%s:%s@%s(%s:%s)/%s",
		config.DbUser, config.DbPwd, config.DbProtocol,
		config.DbHost, config.DbPort, config.DbDatabase)
	fmt.Println(sqlPrameter)
	if Db, err = sqlx.Open(config.DbDriver, sqlPrameter); err != nil{
		logs.Debug("失败详情：%s", err.Error())
	}
}

func (this *ShopController)TestBeego(){
	var names []string = []string{"name","bingbing"}
	this.Data["json"] = names
	this.ServeJSON()
}

func (this *ShopController)GetProduct(){
	limit, _ := this.GetInt("limit", 10)
	queryRes := make([]repository.Product, 0)
	fmt.Println("select id,name,age from minishop limit ?", limit)
	if err := Db.Select(&queryRes, "select id,name,age from testcollection limit ?", limit); err != nil {
		logs.Debug("Db.Select 失败 详情：%s", err.Error())
		return
	}

	response := make(map[string]interface{})

	if len(queryRes) > 0{
		response["status"] = 1
		response["data"] = queryRes
		response["msg"] = "获取数据成功"
	} else {
		response["status"] = 0
		response["data"] = queryRes
		response["msg"] = "获取数据失败"
	}

	this.Data["json"] = response
	this.ServeJSON()
}